package cn.qiyu5522.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.constant.SystemConsKeys;
import cn.qiyu5522.domain.VO.BlogUserLoginVO;
import cn.qiyu5522.domain.VO.UserInfoVO;
import cn.qiyu5522.domain.entity.LoginUser;
import cn.qiyu5522.domain.entity.ResponseResult;
import cn.qiyu5522.domain.entity.SystemException;
import cn.qiyu5522.domain.entity.User;
import cn.qiyu5522.enums.AppHttpCodeEnum;
import cn.qiyu5522.service.BlogLoginService;
import cn.qiyu5522.utils.BeanCopyUtils;
import cn.qiyu5522.utils.JwtUtil;
import cn.qiyu5522.utils.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * ClassName: BlogLoginServiceImpl
 * Package: cn.qiyu5522.service.impl
 * Description:
 *
 * @Author: Tonkey
 * @Create：2024/4/11-20:38
 * @Version: v1.0
 */

@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {

        // 调用authenticationManager的 认证方法 ，进行认证
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 判断是否认证通过
        if(ObjectUtil.isNull(authenticate)){
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR);
        }

        // 获取 UserId 生成 token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String token = JwtUtil.createJWT(userId);
        // 把用户信息存入redis
        redisCache.setCacheObject(SystemConsKeys.BLOG_LOGIN +userId,loginUser,SystemConsKeys.REDIS_TTL);
        // 把token 和 userInfo 封装 返回
        // 把 User 转化成 UserInfoVO
        UserInfoVO userInfoVO = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVO.class);
        BlogUserLoginVO blogUserLoginVO = new BlogUserLoginVO(token, userInfoVO);
        return ResponseResult.okResult(blogUserLoginVO);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        // 移除 redis 中的key
        boolean flag = redisCache.deleteObject(SystemConsKeys.BLOG_LOGIN + id);
        if(!flag){
            throw new RuntimeException(new SystemException(AppHttpCodeEnum.NEED_LOGIN));
        }
        return ResponseResult.okResult();
    }
}
